const rule = {
    mobile: /^1[3-9]\d{9}$/,
    email: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
    url: /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/,
    date: /Invalid|NaN/,
    dateISO: /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/,
    number: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
    digits: /^\d+$/,
    idcard: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,

};

// 将日期转换成中文显示
const pareDate = (date, format) => {
    const formatDate = date.toString().replace(/-/g, '/');
    const da = new Date(formatDate);
    const year = da.getFullYear() + "年";
    const month = da.getMonth() + 1 + "月";
    const day = da.getDate() + "日";
    const h = da.getHours() > 9 ? da.getHours() : "0" + da.getHours();
    const mm = da.getMinutes() > 9 ? da.getMinutes() : "0" + da.getMinutes();
    let text;
    switch (format) {
        case "年月日时分":
            text = `${year}${month}${day} ${h}:${mm}`;
            break;
        case "年月日":
            text = `${year}${month}${day}`;
            break;
        case "月日":
            text = `${month}${day}`;
            break;
    }
    return text;
};

// 判断空对像
const isEmptyObject = (obj) => {
    for (var key in obj) {
        return false
    };
    return true
};


const isObject = (val) => {
    return Object == val.constructor;
}


/**
根据身份证号码判断性别
15位身份证号码：第7、8位为出生年份(两位数)，第9、10位为出生月份，第11、12位代表出生日
18位身份证号码：第7、8、9、10位为出生年份(四位数)，第11、第12位为出生月份，
第13、14位代表出生日期，第17位代表性别，奇数为男，偶数为女。
*/
// 根据身份证号获取年龄
const getAge = (identityCard) => {
    var len = (identityCard + "").length;
    var strBirthday = "";
    if (len == 18)//处理18位的身份证号码从号码中得到生日和性别代码
    {
        strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
    }
    if (len == 15) {
        var birthdayValue = '';
        birthdayValue = identityCard.charAt(6) + identityCard.charAt(7);
        if (parseInt(birthdayValue) < 10) {
            strBirthday = "20" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
        } else {
            strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
        }

    }
    // 时间字符串里，必须是“/”
    var birthDate = new Date(strBirthday);
    var nowDateTime = new Date();
    var age = nowDateTime.getFullYear() - birthDate.getFullYear();
    // 再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
    if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
};

// 根据身份证号码判断是否达到70岁
const isSeventyYearsOld = (idcard) => {
    const age = getAge(idcard);
    if (age >= 70) {
        return true;
    } else {
        return false;
    }

};


const urlSearch = () => {          // 获取导航栏地址url参数
    let queryArr = [];
    let str = location.href;      // 取得整个地址栏
    let num = str.indexOf("?")
    str = str.substr(num + 1);    // 取得所有参数   stringvar.substr(start [, length ]

    let arr = str.split("&");     // 各个参数放到数组里
    for (let i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            queryArr.push({
                name: arr[i].substring(0, num),
                value: arr[i].substr(num + 1)
            }
            )
        }
    }
    return queryArr;
};

const isHasAgentId = () => { // 判断url是否包含有分销id
    const arr = urlSearch(),
        len = arr.length;
    let newArr = [];
    if (len) {
        newArr = arr.filter(item => item.name == "agent_id");
    }
    return newArr.length > 0 ? true : false;
};

const setUrl = () => {                         // 根据获取到的url给其添加上分销id
    const agentId = localStorage.getItem("mid"); // 从本地存储中获取分销ID（mid）
    const sid = localStorage.getItem(`sid`) ? localStorage.getItem(`sid`) : ''; // 从本地存储中获取分销ID（sid）
    const flag = isHasAgentId();        // 判断地址里是否包含分销ID
    let url = location.href;
    const len = urlSearch().length;
    if (agentId != null && !flag) {
        if (len) {
            url = `${url}&agent_id=${agentId}&sid=${sid}`;
        } else {
            url = `${url}?agent_id=${agentId}&sid=${sid}`;
        }
    } else {
        if (len) {
            url = `${url}&sid=${sid}`;
        } else {
            url = `${url}?sid=${sid}`;
        }
    }
    return url;
};



// 设置本地存储过期时间
const dtime = '_deadtime';
/**
 * 设置本地存储
 * @param {*} k 存储的key
 * @param {*} v 存储的value
 * @param {*} t 设置过期时间 30 * 60
 */
const setLocalStorage = (k, v, t) => {
    localStorage.setItem(k, v);
    const seconds = parseInt(t);
    if (seconds > 0) {
        let timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000 + seconds;
        localStorage.setItem(k + dtime, timestamp + "");
    } else {
        localStorage.removeItem(k + dtime);
    }
};

/**
 * 获取本地存储
 * @param {*} k 存储的key 
 * @param {*} def 默认值
 */
const getLocalStorage = (k, def) => {
    const deadtime = parseInt(localStorage.getItem(k + dtime));
    if (deadtime) {
        if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
            if (def) {
                return def;
            } else {
                return;
            }
        }
    }
    const res = localStorage.getItem(k);
    if (res) {
        return res;
    } else {
        return def;
    }
};

export default {
    rule,               // 正则
    pareDate,           // 将日期转换成中文显示
    isEmptyObject,      // 判断空对像
    isObject,           // 判断是否是对象
    setLocalStorage,    // 设置本地存储可过期
    getLocalStorage,    // 获取本地存储
    getAge,             // 根据身份证号获取年龄
    isSeventyYearsOld,  // 根据身份证号码判断是否达到70岁
    urlSearch,          // 获取导航栏地址url参数
    isHasAgentId,       // 判断url是否包含有分销id
    setUrl,             // 根据获取到的url给其添加上分销id
}